using System.Collections.Generic;
using UnityEngine;

public class ItemSpawner : MonoBehaviour
{
    public static ItemSpawner Instance;
    public GameObject[] itemPrefabs; // 物品预设
    private int itemCount; // 要生成的物品数量
    public GameObject spawnAreaSize; // 生成区域大小的 GameObject

    private List<Vector3> spawnedPositions = new List<Vector3>(); // 已生成物品的位置列表

    private void Awake() {
        Instance = this;
    }

    void Start()
    {
        SpawnItems();
    }

    public void SpawnItems()
    {
        // 循环遍历子物体
        for (int i = transform.childCount - 1; i >= 0; i--)
        {
            // 获取当前子物体
            Transform child = transform.GetChild(i);

            // 销毁子物体
            Destroy(child.gameObject);
        }

        itemCount = Random.Range(5, 10);
        for (int i = 0; i < itemCount; i++)
        {
            Vector3 randomPosition = GetRandomPosition();
            GameObject itemPrefab = itemPrefabs[Random.Range(0, itemPrefabs.Length)];

            GameObject newItem = Instantiate(itemPrefab, randomPosition, Quaternion.identity);
            newItem.transform.parent = transform;
            spawnedPositions.Add(randomPosition);
        }
    }

    Vector3 GetRandomPosition()
    {
        Vector3 spawnSize = spawnAreaSize.transform.localScale;
        Vector3 randomPosition = new Vector3(Random.Range(spawnAreaSize.transform.position.x - spawnSize.x / 2, spawnAreaSize.transform.position.x + spawnSize.x / 2),
                                             Random.Range(spawnAreaSize.transform.position.y - spawnSize.y / 2, spawnAreaSize.transform.position.y + spawnSize.y / 2),
                                             Random.Range(spawnAreaSize.transform.position.z - spawnSize.z / 2, spawnAreaSize.transform.position.z + spawnSize.z / 2));

        // 检查生成的位置是否与已有的物品位置重叠
        while (CheckOverlap(randomPosition))
        {
            randomPosition = new Vector3(Random.Range(spawnAreaSize.transform.position.x - spawnSize.x / 2, spawnAreaSize.transform.position.x + spawnSize.x / 2),
                                         Random.Range(spawnAreaSize.transform.position.y - spawnSize.y / 2, spawnAreaSize.transform.position.y + spawnSize.y / 2),
                                         Random.Range(spawnAreaSize.transform.position.z - spawnSize.z / 2, spawnAreaSize.transform.position.z + spawnSize.z / 2));
        }

        return randomPosition;
    }

    bool CheckOverlap(Vector3 position)
    {
        foreach (Vector3 spawnedPos in spawnedPositions)
        {
            if (Vector3.Distance(position, spawnedPos) < 1.0f ) // 这里的1.0f是一个简单的重叠检测距离阈值
            {
                return true;
            }
        }
        return false;
    }
}
